package com.sky.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sky.pojo.TestPojo;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Content:
 * @Author: Asen
 * @Date: 2023/9/24 19:35
 */
@MappedTypes({List.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public abstract class ListJsonTypeHandler<T> extends BaseTypeHandler<List<T>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<T> ts, JdbcType jdbcType) throws SQLException {
        String content = CollUtil.isEmpty(ts)?null:JSON.toJSONString(ts);
        preparedStatement.setString(i,content);
    }

    @Override
    public List<T> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return this.getListByJsonArrayString(resultSet.getString(s));
    }

    @Override
    public List<T> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return this.getListByJsonArrayString(resultSet.getString(i));
    }

    @Override
    public List<T> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return this.getListByJsonArrayString(callableStatement.getString(i));
    }

    private List<T> getListByJsonArrayString(String content){
        return StrUtil.isBlank(content)?new ArrayList<>():JSON.parseObject(content,this.specificType());
    }

    protected abstract TypeReference<List<T>> specificType();
}
